<template>
  <div class="upload-container">
    <div v-if="isEmpty" class="empty-block">
      <icon-empty />
      <div class="text">暂无数据</div>
    </div>
    <a-upload
      v-else
      ref="uploadRef"
      v-model:file-list="uploadValue"
      :action="uploadAction"
      :limit="1"
      :auto-upload="false"
      :disabled="disabled"
      draggable
      name="files"
      @before-upload="beforeUpload"
      @change="uploadChange"
    >
      <!-- 上传按钮 -->
      <template #upload-button>
        <div class="upload-op-block">
          <div class="upload-icon"><icon-plus /></div>
          <a-space direction="vertical" :size="4" fill>
            <div style="color: #1d2129">点击或拖拽文件到此处上传</div>
            <div style="font-size: 12px; color: #86909c">仅支持{{ accept.join('、') }}格式，最大文件不超过{{ maxMB }}MB</div>
          </a-space>
        </div>
      </template>
      <template #upload-item="{ fileItem }">
        <a-spin
          :tip="`${fileItem.status == 'init' ? '压缩中 ' : '上传中 '}${parseInt(fileItem.percent * 100)}%`"
          :loading="['init', 'uploading'].includes(fileItem.status)"
        >
          <div class="upload-item-block">
            <!-- 文件 -->
            <div class="pdf-cont" v-if="(fileType = geFileTypeFn(fileItem)) != 'img'">
              <img :src="pdfIcon" v-if="fileType == 'pdf'" width="48" />
              <img :src="docIcon" v-else width="48" />
              <div class="filename">{{ fileItem.name }}</div>
            </div>
            <div style="text-align: center" v-else>
              <a-image
                :src="fileItem.url"
                height="214"
                :preview-visible="previewVisible"
                @previewVisibleChange="(e) => (previewVisible = e)"
              />
            </div>

            <div class="action-block">
              <div class="btn"><icon-eye /><span class="text" @click.stop="previewFile(fileItem, fileType)">查看</span> </div>
              <div class="divider" v-if="!disabled"></div>
              <div class="btn" v-if="!disabled"><icon-delete /><span class="text" @click.stop="delItem">删除</span> </div>
            </div>
          </div>
        </a-spin>
      </template>
    </a-upload>
    <!-- 预览pdf -->
    <pdf-viewer
      :url="pdfViewInfo.url"
      :title="pdfViewInfo.title"
      v-model:visible="pdfViewInfo.show"
      @close="Object.assign(pdfViewInfo, { ...PDFDefaultAttr })"
    />
  </div>
</template>

<!-- 仅支持上传单张 -->
<script setup name="DragUpload">
  import { ref, watch, computed, reactive } from 'vue'
  import { getFileInfo } from '@/api/common/index.js'
  import { Message } from '@arco-design/web-vue'
  import pdfIcon from './icons/pdf.png'
  import docIcon from './icons/doc.png'
  import MyCompress from './scripts/upload-compress'

  const props = defineProps({
    modelValue: {
      type: String,
    },
    maxMB: {
      type: Number,
      default: 20,
    },
    disabled: Boolean,
    // 限制选择文件格式
    accept: {
      type: Array,
      default: () => ['PDF', 'JPG', 'PNG'],
    },
  })
  const emit = defineEmits(['update:modelValue', 'change'])
  const uploadRef = ref()
  const isEmpty = computed(() => {
    const modelValue = props.modelValue || []
    if (props.disabled && modelValue.length == 0) {
      return true
    }
    return false
  })
  const uploadAction = import.meta.env.VITE_BASE_PATH + '/uploadFile/commonUpload'
  const uploadValue = ref([])

  // 初始化 before
  const initValueWatch = watch(
    () => props.modelValue,
    (val) => {
      initValueFn(val)
    }
  )
  const initValueFn = (val) => {
    if (val && val.length > 0) {
      // 由于此处需要获取文件名称，需要调用接口
      getFileInfo({ id: val }).then((res) => {
        const result = res.result
        uploadValue.value = [result].map((item) => {
          return {
            uid: item.fileIdStr,
            name: item.originalFileName,
            status: 'done',
            url: `${import.meta.env.VITE_BASE_PATH}/uploadFile/image/${item.fileIdStr}`,
          }
        })
      })
      // 关闭watch
      initValueWatch && initValueWatch()
    }
  }
  // 首先执行一次防止v-if
  initValueFn(props.modelValue)
  // 初始化 end
  // 判断是否是pdf文件
  const geFileTypeFn = (file) => {
    const name = file.name
    const l_name = name.toLocaleLowerCase()
    if (l_name.endsWith('pdf')) {
      return 'pdf'
    }
    if (l_name.endsWith('doc')) {
      return 'doc'
    }
    if (l_name.endsWith('docx')) {
      return 'doc'
    }
    return 'img'
  }
  // pdf预览
  import { PDFDefaultAttr } from '@/components/pdf-viewer/const'
  const pdfViewInfo = reactive({ ...PDFDefaultAttr })
  const previewVisible = ref(false)
  // 预览
  const previewFile = (file, fileType) => {
    console.log(file)
    if (fileType != 'img') {
      if (fileType === 'pdf') {
        // Object.assign(pdfViewInfo, {
        //   url: file.openUrl || file.url,
        //   title: file.name,
        //   show: true,
        // })
        window.open(file.openUrl || file.url)
      } else if (fileType === 'doc') {
        const a = document.createElement('a')
        a.download = file.name
        a.href = file.url
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
      }
      return
    }
    previewVisible.value = true
  }
  // 删除
  const delItem = () => {
    uploadValue.value.length = 0
    emitEvent()
  }
  // 上传之前 限制size
  const beforeUpload = (file) => {
    // 校验文件格式
    const fileName = file.name
    // 限制文件格式
    const accept = props.accept
    const reg = new RegExp(`\\.(${accept.join('|')})$`, 'i')
    if (!reg.test(fileName.toLocaleUpperCase())) {
      Message.error(`文件类型必须是${accept.join(',')},的一种！`)
      return false
    }
    // 限制文件大小（非图片）
    const isNotImg = /^(?!.*\.(jpg|jpeg|png)$).*$/.test(fileName.toLowerCase())
    if (isNotImg) {
      const fileSize = file.size / 1024 / 1024
      if (fileSize > props.maxMB) {
        Message.error(`文件大小不能大于${props.maxMB}MB`)
        return false
      }
    }
    return true
  }
  // 触发emit事件
  const emitEvent = () => {
    const uploadedList = uploadValue.value.filter((item) => item.status == 'done')
    const ids = uploadedList.map((item) => item.uid)
    let res = ids[0]
    emit('update:modelValue', res)
    emit('change', res)
  }
  // 上传变化
  const uploadChange = (fileList, fileItem) => {
    // 文件初始化
    if (fileItem.status == 'init' && fileItem.percent == 0) {
      // 判断是图片，压缩图片
      if (/\.(jpg|jpeg|png)$/.test(fileItem.name.toLowerCase())) {
        MyCompress({
          fileItem: fileItem,
          success: (compressedFile) => {
            // 更新文件，调用 updateFile 方法
            uploadRef.value.updateFile(fileItem.uid, compressedFile)
            // 上传文件，调用 submit 方法
            uploadRef.value.submit(fileItem)
          },
        })
      } else {
        // 上传文件，调用 submit 方法
        uploadRef.value.submit(fileItem)
      }
    } else if (fileItem.status == 'uploading') {
      if (fileItem.percent > 0.99) fileItem.percent = 0.99
    } else if (fileItem.status == 'done') {
      uploadValue.value = fileList.map((item) => {
        if (item.response) {
          item.uid = item.response.result[0].fileIdStr
          // 图片有 url（blod:xxx）重复赋值页面会闪
          if (!item.url) {
            item.url = `${import.meta.env.VITE_BASE_PATH}/uploadFile/image/${item.uid}`
          }
        }
        return item
      })
      emitEvent()

      // 关闭watch
      initValueWatch && initValueWatch()
    }
  }
</script>
<style lang="less" scoped>
  .upload-container {
    position: relative;
    width: 400px;
    height: 214px;
    background: #f2f3f5;
    border-radius: 2px 2px 2px 2px;
    opacity: 1;
    border: 1px solid #e5e6eb;
  }
  .empty-block {
    padding-top: 67px;
    text-align: center;
    color: #b6b6b6;
    font-size: 48px;
    .text {
      font-size: 14px;
      font-weight: 400;
      line-height: 22px;
    }
  }
  .upload-op-block {
    color: var(--color-text-1);
    height: 214px;
    font-size: 12px;
    text-align: center;
    padding: 66px 0;
    font-size: 14px;
    .upload-icon {
      margin-bottom: 26px;
    }
  }
  .upload-item-block {
    width: 400px;
    height: 214px;
    font-size: 12px;
    font-weight: 400;
    color: #ffffff;
    line-height: 22px;

    .pdf-cont {
      padding-top: 67px;
      text-align: center;
      .filename {
        margin-top: 10px;
        font-size: 14px;
        font-weight: 400;
        color: #1d2129;
        line-height: 22px;
      }
    }

    &:hover {
      .action-block {
        display: flex;
      }
    }
    .action-block {
      display: none;
      position: absolute;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      z-index: 1;
      justify-content: center;
      align-items: center;
      border-radius: 0px 0px 2px 2px;
      background: rgba(0, 0, 0, 0.51);
      color: #ffffff;
      .btn {
        font-size: 14px;
        font-weight: 400;
        line-height: 22px;
        height: 22px;
        cursor: pointer;
        .text {
          margin-left: 3px;
        }
        &:hover {
          color: rgb(var(--primary-3));
        }
      }
      .divider {
        margin: 0 16px;
        width: 1px;
        height: 22px;
        border-radius: 0px 0px 0px 0px;
        background: #fff;
        opacity: 1;
      }
    }
  }
</style>
